package work.gac.unbind.v2.unbinder;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import core.encoder.lianwei.PIIDataAESEncoder;
import lombok.extern.slf4j.Slf4j;
import work.gac.unbind.v2.DatalakUtil;
import work.gac.unbind.v2.Setting;

import java.util.concurrent.CopyOnWriteArrayList;

import static work.gac.unbind.v2.Setting.URL.getInfoByPhone;
import static work.gac.unbind.v2.Setting.URL.getInfoUrlByThCode;

/**
 * @author Gong.Yang
 */
@Slf4j
public class LianWeiUnbind implements Unkinder {

    static PIIDataAESEncoder mobileEncoder = new PIIDataAESEncoder(Setting.Fix.secretKey);
    private static final String[] fromSocialCodes = {"阿玛尼会员中心小程序", "阿玛尼会员中心小程序-9EF","阿玛尼会员中心小程序-9VM"};

    @Override
    public boolean match(String tag) {
        return tag.contains("会员中心");
    }

    @Override
    public Runnable process(String thirdCode, String mobile) {
        return () -> {
            try {
                String customerId = getCustomerId(thirdCode, mobile);
                if (StrUtil.isBlank(customerId)) return;
                unbinding(customerId);
                delete(customerId);
            } catch (RuntimeException e) {
                String openId = null;
                for (String fromSocialCode : fromSocialCodes) {
                    String res = DatalakUtil.getOpenId(mobile, fromSocialCode);
                    if (StrUtil.isNotBlank(res)) {
                        openId = res;
                        break;
                    }
                }
                if (StrUtil.isBlank(openId)) {
                    log.error("【LianWei】DL用户 openid为空 mobile->{},thirdCode ->{}", mobile, thirdCode);
                    return;
                }
                DatalakUtil.unbind(mobile, openId);
            }

        };
    }

    /**
     * 获取用户id
     */
    private String getCustomerId(String thirdCode, String mobile) {
        JSONArray content = httpGet(String.format(getInfoUrlByThCode, thirdCode));
        if (!content.isEmpty()) {
            JSONObject user = content.getJSONObject(0);
            return user.get("id", String.class);
        } else {
            if (StrUtil.isBlank(mobile)) return null;
            String encodeMobile = mobileEncoder.encode(mobile);
            JSONArray contentPhone = httpGet(String.format(getInfoByPhone, encodeMobile));
            if (contentPhone.isEmpty()) {
                String notHaveItem = "phone:" + mobile + "  thCode:" + thirdCode;
                log.info("【无该用户】{}", notHaveItem);
                throw new RuntimeException("用户不存在");
            } else {
                JSONObject user = contentPhone.getJSONObject(0);
                return user.get("id", String.class);
            }
        }
    }

    private JSONArray httpGet(String url) {
        HttpRequest request = HttpRequest.get(url).header("Authorization", Setting.Fix.manageToken);
        String response = request.execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(response);
        return jsonObject.getJSONArray("content");
    }


    private static void unbinding(String customerId) {
        try {
            String url = String.format(Setting.URL.unbinding, customerId);
            HttpResponse response = HttpRequest.get(url).header("Authorization", Setting.Fix.manageToken).execute();
            int status = response.getStatus();
            if (status != 200) {
                log.error(response.body());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void delete(String customerId) {
        try {
            String url = String.format(Setting.URL.delete, customerId);
            HttpResponse response = HttpRequest.delete(url).header("Authorization", Setting.Fix.manageToken).execute();
            int status = response.getStatus();
            if (status != 200) {
                log.error("【会员解绑】 删除失败：{}", response.body());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
